package org.aurora.common.delay.queue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * 延迟任务 传入延迟时间 到期后从队列弹出
 **/
public class DelayTask implements Delayed {

    private long delayTimeMillis;   // 延迟时间 ms

    private long endDelayTimeMillis; // 延迟截止时间戳

    public DelayTask(long delayTimeMillis) {
        this.delayTimeMillis = delayTimeMillis;
        this.endDelayTimeMillis = System.currentTimeMillis() + this.delayTimeMillis;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return this.endDelayTimeMillis - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed other) {
        long currentSurplusDelayTimeMillis = getDelay(TimeUnit.MILLISECONDS);
        long otherSurplusDelayTimeMillis = other.getDelay(TimeUnit.MILLISECONDS);

        if (currentSurplusDelayTimeMillis > otherSurplusDelayTimeMillis) {
            return 1;
        } else if (currentSurplusDelayTimeMillis < otherSurplusDelayTimeMillis) {
            return -1;
        } else {
            return 0;
        }
    }

    public long getDelayTimeMillis() {
        return delayTimeMillis;
    }

    public long getEndDelayTimeMillis() {
        return endDelayTimeMillis;
    }
}
